<template>
  <div class="wrapper">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/1'}">跟读管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:'/1'}">跟读列表</el-breadcrumb-item>
      <el-breadcrumb-item>跟读新增</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      <el-row>
        <el-form :model="ruleForm" status-icon :rules="rules1" ref="ruleForm" label-width="100px">
          <el-form-item label="标题" prop="pass" class="form">
            <el-input type="text" v-model="ruleForm.pass" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="上传封面" prop="imageUrl">
            <el-upload
              class="avatar-uploader"
              :action="upload"
              name="files"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon">点我上传</i>
            </el-upload>
          </el-form-item>
          <el-form-item label="跟读内容">
            <table border="1" class="table">
              <tr>
                <th>序号</th>
                <th>英文</th>
                <th>中文</th>
                <th>跟读录音</th>
                <th>操作</th>
                <th class="music">music</th>
              </tr>
              <tr v-for="(content,index) in ruleForm.content" :key="content.key">
                <td>{{index+1}}</td>
                <td class="en">
                  <el-form-item :prop="'content.'+index+'.english'" :rules="[{
                required: true, message: '内容不能为空', trigger: 'blur'},
                {pattern:/^[%&'’,.;=?A-Za-z\s]+$/,message:'亲爱的，这里请输入英文',trigger: 'blur'},
                {max: 50,message: '内容不能超过50个字母哦',trigger:'blur'}]">
                    <el-input v-model="content.english"></el-input>
                  </el-form-item>
                </td>
                <td class="cn">
                  <el-form-item :prop="'content.'+index+'.chinese'" :rules="[{
                    required: true, message: '内容不能为空', trigger: 'blur'},
                     {pattern:/^[%&',，。·~;=?\u4e00-\u9fa5\s]+$/,message:'亲爱的，这里请输入中文',trigger: 'blur'},
                    {max: 20,message: '内容不能超过20个字哦',trigger:'blur'}]">
                    <el-input v-model="content.chinese"></el-input>
                  </el-form-item>
                </td>
                <td class="manu">
                  <el-form-item :prop="'content.'+index+'.src'" :rules="[{
            required: true, message: '音频内容不能为空哦', trigger: 'blur'}]">
                  <el-upload
                    :action="upload"
                    name="files"
                    :before-upload="beforeupload1"
                    :on-success="handleAudioSuccess" :disabled="!content.edit">
                    <el-button size="small" :type="content.src?'danger':'primary'" @click="handleindex(index)">
                      {{content.src?'已上传':'上传文件'}}
                    </el-button>
                  </el-upload>
                  <el-button type="success" @click="letscheck(index)">{{content.flag?'暂停':'播放'}}</el-button>
                  <el-button type="info" @click="handleDel(index)">删除</el-button>
                  </el-form-item>
                </td>
                <td class="red">
                  <el-button type="text" @click="handledel(index)">删除行</el-button>
                  <el-button type="text" @click="insert(index)">插入行</el-button>
                </td>
                <td class="music">
                  <audio :src="content.src"></audio>
                </td>
              </tr>
            </table>
          </el-form-item>
          <el-form-item label="发布老师" prop="teacher">
            <el-select v-model="ruleForm.teacher" placeholder="请选择">
              <el-option
                v-for="item in ruleForm.options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="老师寄语" prop="desc">
            <el-input type="textarea" v-model="ruleForm.desc"></el-input>
          </el-form-item>
          <el-form-item label="上线日期" prop="value2">
            <el-date-picker class="setuptime"
                            v-model="ruleForm.value2"
                            type="date" :picker-options="pickerOptions1" @change="timechange">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="goback">返回</el-button>
            <el-button @click="handlesub('ruleForm')">提交</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </div>
  </div>
</template>

<script>
  import {readingmess, readingadd, readingfiles} from '@/api/readingmanagement/reading'
  import {teachername} from '@/api/slider/slider'
  import {setCookie, getCookie, delCookie, setItem, removeItem, getItem} from '@/api/cookies/cookies'

  export default {
    name: "ReadingNewadd",
    props:{
      upload:String
    },
    data() {
      var validatePass = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('标题不能为空'));
        }
        setTimeout(() => {
          if (/^.{3,10}$/.test(value) == false) {
            return callback(new Error('请输入3到10个字以内的标题'))
          } else {
            callback();
          }
        }, 1000)
      };
      var validateen = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('内容不能为空'));
        }
        setTimeout(() => {
          if (/^.{3,20}$/.test(value) == false) {
            return callback(new Error('请输入20个字以内的跟读内容'))
          } else {
            if (/^[\u4e00-\u9fa5]{0,}$/.test(value) == false) {
              callback(new Error('请输入中文'));
            } else {
              callback();
            }
          }
        }, 1000);
      };
      var validatecn = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('内容不能为空'));
        }
        setTimeout(() => {
          if (/^.{3,20}$/.test(value) == false) {
            return callback(new Error('请输入20个字以内的跟读内容'))
          } else {
            if (/^[\u4e00-\u9fa5]{0,}$/.test(value) == false) {
              callback(new Error('请输入中文'));
            } else {
              callback();
            }
          }
        }, 1000);
      };
      return {
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
        loading: false,
        saved: false,
        ruleForm: {
          pass: '',
          state:'',
          imageUrl: '',
          value2: '',
          teacher: '',
          readBelong: '',
          checkPass: '',
          input: 1,
          options: [],
          en: '',
          desc: '',
          index: '',
          content: [],
          insert: {
            english: '',
            chinese: '',
            src: '',
            flag: false,
            edit: true
          }
        },
        rules1: {
          pass: [
            {validator: validatePass, trigger: 'blur'}
          ],
          chinese: [
            {validator: validatecn, trigger: 'blur'}
          ],
          english: [
            {validator: validateen, trigger: 'blur'}
          ],
          imageUrl: [
            {required: true, message: '请上传一张封面图片', trigger: 'blur'}
          ],
          desc: [
            {required: true, message: '请发布一条老师寄语哦', trigger: 'blur'}
          ],
          teacher: [
            {required: true, message: '请选择发布老师', trigger: 'change'}
          ],
          value2: [
            {required: true, message: '请选择上线时间', trigger: 'blur'}
          ]
        }
      };
    },
    methods: {
      handleslider() {
        let _this = this;
        for(let i=0;i<6;i++){
          this.ruleForm.content.push({
            src: '',
            edit: true,
            chinese: '',
            english: '',
            flag: false,
            id: '',
            key: i
          })
        }
        teachername().then(function (res) {
          if (res.status == 200) {
            for (let item of res.data.UserList) {
              _this.ruleForm.options.push({
                value: item.id,
                label: item.name + '老师, ID ' + item.id
              })
            }
          }
        })
      },
      handleindex(index) {
          this.index = index;
      },
      timechange(val){
        let date=new Date();
        if(this.$moment(val.valueOf()).format("D")==date.getDate()){
              this.ruleForm.state="1"
        }else {
          this.ruleForm.state="2"
        }
      },
      handleAudioSuccess(response) {
        let arr = [];
        for (let i = 0; i < this.ruleForm.content.length; i++) {
          if (localStorage.getItem(i) !== null && localStorage.getItem(i) == response.fileName) {
            this.ruleForm.content[i].src = response.URLList[0].url
          }
        }
      },
      handleAvatarSuccess(response) {
        this.ruleForm.imageUrl = response.URLList[0].url;
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        let _this = this;
        return isLt2M;
      },
      beforeupload1(file) {
        localStorage.setItem(this.index, file.name);
        const isLt2M = file.size / 1024 / 1024 < 10;
        console.log(file.size / 1024 / 1024);
        const isMP3 = file.type === 'audio/mp3' || 'audio/ogg';
        if (!isLt2M) {
          this.$message.error('上传音频最好不要超过10MB哦，您可以多读几条分开上传');
          return isLt2M;
        }
        if (!isMP3) {
          this.$message.error('请上传音频格式的文件哦');
          return isMP3;
        }
        return isLt2M && isMP3
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handlefiles(res) {
        for (let item of res.data.messlist) {
          this.ruleForm.readBelong += item.id + ','
        }
        return this.ruleForm.readBelong;
      },
      handleupload(res) {
        let params = {};
        params.readBelong = res;
        params.state=this.ruleForm.state;
        params.createBy = this.ruleForm.teacher;
        params.title = this.ruleForm.pass;
        params.nameImg = this.ruleForm.imageUrl;
        params.message = this.ruleForm.desc;
        params.uploadTime = this.ruleForm.value2.valueOf();
        let _this = this;
        readingadd(params).then(function (res) {
          console.log(res);
          if (res.data.code == 2) {
            _this.$message.error('时间线有冲突请重新重新选择发布日期');
            for (let i = 0; i < 10; i++) {
              localStorage.removeItem(i);
            }
          }
          else {
            _this.$message({
              message: '发布成功',
              type: 'success'
            });
            _this.$router.push({name: 'ReadingManagement'})
          }
        })
      },
      handlesub(ruleForm) {
        let _this = this;
        this.$refs[ruleForm].validate((valid) => {
          if (valid&&this.ruleForm.content[0].src!==null) {
            let mess = [];
            for (let item of _this.ruleForm.content) {
              mess.push({
                messCN: item.chinese,
                messEN: item.english,
                mess: item.src
              })
            }
            _this.$confirm('确定提交跟读任务吗', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              for (let i = 0; i < 10; i++) {
                localStorage.removeItem(i);
              }
              let time=this.ruleForm.value2.valueOf();
              readingfiles(JSON.stringify(mess),time).then(_this.handlefiles).then(_this.handleupload);
            }).catch(() => {
              _this.$message({
                type: 'info',
                message: '已取消提交'
              });
            });
          } else {
            this.$message.error('内容填写不完整');
            return false;
          }
        })
      },
      letscheck(index) {
        var play = document.getElementsByTagName('audio');
        for (var i = 0; i < this.ruleForm.content.length; i++) {
          if (i == index) {
            if (!this.ruleForm.content[index].flag) {
              play[index].play();
              this.ruleForm.content[index].flag = true;
              console.log(this.ruleForm.content[index].flag);
            } else {
              play[index].pause();
              this.ruleForm.content[index].flag = false;
            }
          } else {
            play[i].pause();
            this.ruleForm.content[i].flag = false;
          }
        }
      },
      handleDel(index) {
        console.log(index);
        this.ruleForm.content[index].src = '';
        this.ruleForm.content[index].id = ''
      },
      handledel(index) {
        if (this.ruleForm.content.length < 7) {
          alert("您最少需要6行")
        } else {
          this.ruleForm.content.splice(index, 1)
        }
      },
      insert(index) {
        if (this.ruleForm.content.length > 9) {
          alert("最多10行")
        } else {
          this.ruleForm.content.splice(index + 1, 0, {
            src: '',
            edit: true,
            chinese: '',
            english: '',
            flag: false,
            id: '',
            key: Date.now()
          });
          console.log(this.ruleForm.content);
        }
      },
      goback() {
        this.$confirm('您还未提交数据。确认离开当前页面吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          for (let i = 0; i < 10; i++) {
            localStorage.removeItem(i);
          }
          this.$router.push({
            path: '/1' +
            ''
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消跳转'
          });
        });
      },
    },
    mounted() {
      this.handleslider();
      for (let i = 0; i < 10; i++) {
        localStorage.removeItem(i);
      }
    }
  }
</script>

<style lang="less" scoped>
  @import "~styles/z.less";
  @import "~styles/css3.less";
  @import "~styles/variables.less";

  .el-cascader-menus {
    top: 857px !important;
  }

  .table[data-v-05dccde1] {
    margin-left: 1px;
  }

  /deep/ .el-upload-list__item-name {
    display: none;
  }

  /deep/ .el-upload-list__item-status-label {
    display: inline;
    left: 3px;
    top: 10px;
  }

  .wrapper {
    .w100;
  }

  td {
    height: 100px;
  }

  .avatar-uploader /deep/ .el-upload {
    border: 5px dashed lightgrey;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader /deep/ .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .table {
    border: 2px solid lightgrey;
    margin-bottom: 20px;
    margin-left: 20px;
    width: 95%;
    th {
      height: 40px;
      text-align: center;
      width: 40px;
    }
    td /deep/ .el-input__inner {
      height: 43px;
      font-size: 13px;
      box-shadow: none;
      border: none;
    }
    td {
      text-align: center;
    }
    .en, .cn {
      width: 270px;
      height: 70px;
    }
    .manu {
      .flex;
      padding: 15px 0;
      justify-content: center;
      align-items: center;
      button {
        width: 60px;
        height: 30px;
      }
      & button:first-child {
        width: 70px;
      }
      /deep/ .el-form-item__content{
        width:240px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
    .red {
      width: 80px;
      & button:first-child {
        color: red;
      }
    }
    .music {
      display: none;
    }
    audio {
      opacity: 1;
      height: 0;
    }
  }
</style>
